import cv2
import distance

def init_tracker(frame, box):
    tracker = cv2.legacy.TrackerKCF_create()
    tracker.init(frame, box)
    return tracker


# width_in_frame = abs(int(xyxy[2]) - int(xyxy[0]))
# if width_in_frame != 0:
# width_in_frame = width_in_frame*3/10
# disval = distance.distance_finder(distance.focal_length_found, distance.HEIGHT, width_in_frame)
# p1, p2 = (int(xyxy[0]), int(xyxy[1])), (int(xyxy[2]), int(xyxy[3]))
# if label:
#     tf = max(lw - 1, 1)  # font thickness
#     w, h = cv2.getTextSize(label, 0, fontScale=lw / 5, thickness=tf)[0]  # text width, height
#     outside = int(xyxy[1]) - h - 3 >= 0
#     label = str(round(disval, 2))+'m'
#     cv2.putText(im0, label, (p1[0], p1[1] - 2 if outside else p1[1] + h + 2), 0, lw/3, (255, 255, 255),
#                 thickness=tf, lineType=cv2.LINE_AA)
# cv2.line(im0, (int(W/2), int(H)), ((int(xyxy[0])+int(width_in_frame/2)), int(xyxy[3])), (0, 0, 255), 3, 8)#im0.shape[1]w  im0.shape[0]h
def update_track_frame(tracker, frame, Image_H, Image_W):
    out_box = None
    (success, box) = tracker.update(frame)
    lw = max(round(sum(frame.shape) / 2 * 0.003), 2)
    if success:
        (x, y, w, h) = [int(v) for v in box]
        p1 = (x, y)
        out_box = [(x, y, w, h)]
        cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
        center_in_frame = distance.cal_displot(((x+w/2), (y+h)), ((Image_W/2), Image_H))
        center_in_frame = 800 - center_in_frame
        disval = distance.distance_finder(distance.focal_length_found, distance.HEIGHT, center_in_frame)
        tf = max(lw - 1, 1)  # font thickness
        label = str(round(disval, 2)) + 'm'
        labelw, labelh = cv2.getTextSize(label, 0, fontScale=lw / 5, thickness=tf)[0]  # text width, height
        outside = int(y) - labelh - 3 >= 0
        cv2.putText(frame, label, (p1[0], p1[1] - 2 if outside else p1[1] + labelh + 2), 0, lw / 3, (255, 255, 255),
                        thickness=tf, lineType=cv2.LINE_AA)

        # im0.shape[1]w  im0.shape[0]h
        # cv2.line(frame, ((Image_W/2), Image_H), ((x+w/2), (y+h)), (0, 0, 255), 3, 8)


    if out_box != None:
        print(w, h, (480-(y+h)), center_in_frame)
        return out_box

    return None


